package com.deyinet.bdcms.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.deyinet.bdcms.controller.dtoandapi.ExcelDataApi;
import com.deyinet.bdcms.controller.dtoandapi.ExcelDeviceApi;
import com.deyinet.bdcms.controller.dtoandapi.RedisDeviceApi;
import com.deyinet.bdcms.core.vo.Page;
import com.deyinet.bdcms.entity.*;
import com.deyinet.bdcms.service.*;
import com.deyinet.bdcms.tools.*;
import org.apache.commons.collections.map.HashedMap;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Bacel on 2017/04/16.
 */
@Controller
@RequestMapping(value = "/sysmanage/device")
public class deviceController {
    private final Logger logger = Logger.getLogger(deviceController.class);

    @Autowired
    private IDeviceService moduleService;
    @Autowired
    private IDeviceownerService deviceownerService;
    @Autowired
    private ISysmoduleService sysmoduleService;
    @Autowired
    private ILogsService logsService;
    @Autowired
    private IDevicedataService devdataService;


    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public void list() {
    }

    @RequestMapping(value = "/typelist", method = RequestMethod.GET)
    public void typelist() {
    }


    @RequestMapping(value = "/add")
    public void add(String sn, Model model) {
        model.addAttribute("sn", sn);
    }

    @RequestMapping(value = "/edit")
    @ResponseBody
    public Map<String, Object> edit(Device module,HttpServletRequest request) {
        Map<String, Object> info = new HashMap<>();
        Syslog log = new Syslog();
        Sysmodule sysmodule=new Sysmodule();
        Jedis redis = RedisPoolUtils.getJedisObject();
        info.put("content", "操作失败");
        Device old = moduleService.get(module.getSn());
        if (old != null) {
            old.setDevicename(module.getDevicename());
            old.setImei(module.getImei());
            old.setImsi(module.getImsi());
            old.setDeviceinfo(module.getDeviceinfo());
            old.setLat(module.getLat());
            old.setLng(module.getLng());
            old.setDevicemodel(module.getDevicemodel());
            old.setLocation(module.getLocation());
            old.setUpper(module.getUpper());
            old.setLower(module.getLower());
            old.setReportCycle(module.getReportCycle());
            old.setSampleCycle(module.getSampleCycle());
            if (module.getOwnerid()!=null){
                Deviceowner owner=deviceownerService.get(module.getOwnerid());
                module.setDeviceownerByOwnerid(owner);
            }else {
                old.setDeviceownerByOwnerid(null);
            }
            old.setLat(module.getLat());
            moduleService.updateT(old);
            info.put("content", "修改成功");
            log.setTitle("修改设备信息");//日志内容
            log.setContent("修改sn为"+old.getSn()+"的设备");
        } else {
            if (module.getOwnerid()!=null){
                Deviceowner owner=deviceownerService.get(module.getOwnerid());
                module.setDeviceownerByOwnerid(owner);
            }

            module.setCreatedate(new Timestamp(System.currentTimeMillis()));
            moduleService.insertT(module);
            info.put("content", "添加成功");
            log.setTitle("添加设备信息");//日志内容
            log.setContent("添加了sn为"+module.getSn()+"的设备");
        }
        try {
            Device device = moduleService.load(module.getSn());
            String s = redis.hget(RedisPoolUtils.dbname,module.getSn());
            RedisDeviceApi api;
            if (s!=null){
                api= JSON.parseObject(s, RedisDeviceApi.class);
            }else {
                api=new RedisDeviceApi();
            }
            Pipeline p = redis.pipelined();
            Map<String, String> data = new HashMap<>();
            api.setDeviceName(device.getDevicename());
            api.setUpper(device.getUpper());
            api.setLower(device.getLower());
            api.setLocation(device.getLocation());
            api.setLat(device.getLat());
            api.setLng(device.getLng());
            api.setImei(device.getImei());
            api.setImsi(device.getImsi());
            api.setReportCycle(device.getReportCycle());
            api.setDeviceCreateTime(device.getCreatedate());
            api.setSampleCycle(device.getSampleCycle());
            api.setDeviceInfo(device.getDeviceinfo());
            api.setDeviceModel(device.getDevicemodel());
            if (device.getDeviceownerByOwnerid()!=null) {
                api.setDeviceOwner(device.getDeviceownerByOwnerid().getName());
            }else {
                api.setDeviceOwner(null);
            }
            data.put(device.getSn(), JSON.toJSONString(api));
            p.hmset(RedisPoolUtils.dbname, data);
            p.sync();
            p.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            redis.close();
        }

        sysmodule.setId(4);//根据数据库sysmodule表的对应的id去set
        log.setSysmoduleByModuleid(sysmodule);
        log.setSysuserByUserid(WebUtilify.LoginUserinfo(request));
        log.setCreatedate(new Timestamp(System.currentTimeMillis()));
        WebUtilify.WriteLog(request,log, logsService);
        info.put("Message", "ok");
        return info;
    }

    @RequestMapping(value = "/listdata")
    @ResponseBody
    public String listdata(HttpServletRequest request, Page<Device> page) {
        String name = request.getParameter("deviceName");
        String ownerName= request.getParameter("ownerName");
        String deviceInfo= request.getParameter("deviceInfo");
        String deviceModel= request.getParameter("deviceModel");
        Device device = new Device();
        if(name!=null&&!"".equals(name)){
              device.setDevicename(name);
        }
         if(ownerName!=null&&!"".equals(ownerName)){
             Deviceowner owner=new Deviceowner();
             owner.setName(ownerName);
             device.setDeviceownerByOwnerid(owner);
        }
        if(deviceInfo!=null&&!"".equals(deviceInfo)){
           device.setDeviceinfo(deviceInfo);
        }
        if(deviceModel!=null&&!"".equals(deviceModel)){
            device.setDevicemodel(deviceModel);
        }
        moduleService.getPageByExampleLike(device, page);
        Map<String, Object> info = new HashMap<>();
        info.put("totalRow", page.getTotalRow());
        info.put("pageCurrent", page.getPageCurrent());
        info.put("list", page.getList());
        String ret = JSON.toJSONString(info, SerializerFeature.DisableCircularReferenceDetect);// JSONArray.toJSONString(datamodule);
        return ret;
    }

    @RequestMapping(value = "/listdataimport")
    public void listdataimport(Device device,final HttpServletRequest request, final HttpServletResponse response) throws ParseException, IOException {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String name = request.getParameter("deviceName2");
        String ownerName= request.getParameter("ownerName2");
        String deviceInfo= request.getParameter("deviceInfo2");
        String deviceModel= request.getParameter("deviceModel2");
        if(name!=null&&!"".equals(name)){
            device.setDevicename(name);
        }
        if(ownerName!=null&&!"".equals(ownerName)){
            Deviceowner owner=new Deviceowner();
            owner.setName(ownerName);
            device.setDeviceownerByOwnerid(owner);
        }
        if(deviceInfo!=null&&!"".equals(deviceInfo)){
            device.setDeviceinfo(deviceInfo);
        }
        if(deviceModel!=null&&!"".equals(deviceModel)){
            device.setDevicemodel(deviceModel);
        }
        List<Device> list = moduleService.findByExampleLikeImport(device);
        List<ExcelDeviceApi> listData = null;
        if (list.size() > 0) {
            listData = setToExcelApi(list);
            Map<String, Object> map = new HashedMap();
            Map<String, String> ziDuan = new HashMap();
            ziDuan.put("0sn", "sn");
            ziDuan.put("1devicename", "设备名称");
            ziDuan.put("2imei", "imei");
            ziDuan.put("3imsi", "imsi");
            ziDuan.put("4deviceinfo", "设备信息");
            ziDuan.put("5location", "设备位置");
            ziDuan.put("6ownerName", "所属用户");
            ziDuan.put("7devicemodel", "设备型号");
            ziDuan.put("8upper", "水位上限");
            ziDuan.put("9lower", "水位下限");
            ziDuan.put("AreportCycle", "上报周期");
            ziDuan.put("BsampleCycle", "采样周期");
            ziDuan.put("Ccreatedate", "创建时间");
            map.put("listData", listData);
            map.put("ziDuan", ziDuan);
            File file = objListToExcel.objListToExcel("设备列表", map);
            byte[] b = FileTool.getBytesFromFile(file);
            //以字符流的形式下载文件
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=device-"+format.format(new Date())+".xls");
            response.addHeader("content-type","utf-8");
            response.addHeader("Content-Length", "" + b.length);
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(b);
            toClient.flush();
            toClient.close();
        }
    }


    @RequestMapping(value = "/del")
    @ResponseBody
    public Map<String, Object> del(String json, HttpServletRequest request) {
        Syslog log = new Syslog();
        Sysmodule sysmodule=new Sysmodule();
        List<Device> devices = JSONArray.parseArray(json, Device.class);
        String[] idarr = new String[devices.size()];
        String content = "";
        for (int i = 0; i < devices.size(); i++) {
            idarr[i] = devices.get(i).getSn();
            content+=idarr[i];
            if (i!=devices.size()-1){
                content+=",";
            }
        }
        moduleService.batchDelete(idarr);
        log.setTitle("删除设备信息");
        sysmodule.setId(4);//根据数据库sysmodule表的对应的id去set
        log.setSysmoduleByModuleid(sysmodule);
        log.setSysuserByUserid(WebUtilify.LoginUserinfo(request));
        log.setContent("删除id为"+content+"的设备");
        log.setCreatedate(new Timestamp(System.currentTimeMillis()));
        WebUtilify.WriteLog(request,log, logsService);

        Jedis redis = RedisPoolUtils.getJedisObject();
        redis.hdel(RedisPoolUtils.dbname,idarr);
        redis.close();
        Map<String, Object> info = new HashMap<>();
        info.put("message", "删除成功");
        info.put("status", 200);
        return info;
    }

    @RequestMapping(value = "/getmodule", method = RequestMethod.POST)
    @ResponseBody
    public Device getmodule(HttpServletRequest request, String sn)
            throws Exception {
        return moduleService.get(sn);
    }

    private List<ExcelDeviceApi> setToExcelApi(List<Device> list){
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<ExcelDeviceApi> apis=new ArrayList<>();
        for (Device device:list) {
            ExcelDeviceApi api=new ExcelDeviceApi();
            api.setSn(device.getSn());
            api.setDevicename(device.getDevicename());
            api.setImei(device.getImei());
            api.setImsi(device.getImsi());
            api.setDeviceinfo(device.getDeviceinfo());
            api.setLocation(device.getLocation());
            if (device.getDeviceownerByOwnerid()!=null){
                api.setOwnerName(device.getDeviceownerByOwnerid().getName());
            }
            api.setDevicemodel(device.getDevicemodel());
            api.setUpper(device.getUpper());
            api.setLower(device.getLower());
            api.setReportCycle(device.getReportCycle());
            api.setSampleCycle(device.getSampleCycle());
            api.setCreatedate(sdf.format(device.getCreatedate()));
            apis.add(api);
        }
        return apis;
    }

}